package io.shallwe._admin.basedata.scanner;

import java.util.Date;
import java.util.List;
import com.jfinal.aop.Aop;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import com.jfinal.plugin.ehcache.CacheKit;
import io.shallwe._admin.account.AdminAccountService;
import io.shallwe.common.model.Account;
import io.shallwe.common.model.Scanner;

public class ScannerService {

	AdminAccountService accountService = Aop.get(AdminAccountService.class);
	
	private Scanner dao=Scanner.dao;

	/**
	 * 查出所有扫描枪信息
	 * @return
	 */
	public List<Scanner> listAllScanner(){
		List<Scanner> ret = CacheKit.get("scanner","all");
		if(ret==null){
			ret = dao.template("scanner.listAllScanner").find();
			CacheKit.put("scanner","all",ret);
		}
		return  ret;
	}

	/***
	 * 根据 ID 查找 扫码枪信息
	 * @param id
	 * @return
	 */
	public Scanner findById(Integer id){
		Scanner ret =CacheKit.get("findScannerById",id);
		if(ret==null){
			List<Scanner> scanners = this.listAllScanner();
			for (Scanner scanner: scanners) {
				if(scanner.getId().intValue()==id.intValue()){
					ret = scanner;
					CacheKit.put("findScannerById",id,ret);
					break;
				}
			}
		}
		if(ret==null){
			ret = dao.findById(id);
			CacheKit.put("findScannerById",id,ret);
		}

		return  ret;
	}

	/***
	 * 查出所有手动上线扫描枪
	 * @return
	 */
	public  List<Scanner> listManualEnterScanner(){
		List<Scanner> ret = CacheKit.get("listScannerByType",Scanner.MANUAL_ENTER);
		if(ret==null){
			ret = dao.template("scanner.listScannerByType",Scanner.MANUAL_ENTER).find();
			CacheKit.put("listScannerByType",Scanner.MANUAL_ENTER,ret);
		}
		return  ret;
	}

	/***
	 * 查出所有手动下线扫描枪
	 * @return
	 */
	public  List<Scanner> listManualExitScanner(){
		List<Scanner> ret = CacheKit.get("listScannerByType",Scanner.MANUAL_EXIT);
		if(ret==null){
			ret = dao.template("scanner.listScannerByType",Scanner.MANUAL_EXIT).find();
			CacheKit.put("listScannerByType",Scanner.MANUAL_EXIT,ret);
		}
		return  ret;
	}


	/**
	 * 根据IP地址查询扫描枪信息
	 * @param ip
	 * @return
	 */
	public Scanner findByIp(String ip) {
		Scanner ret =CacheKit.get("findScannerByIp",ip);
		if(ret==null){
			List<Scanner> scanners = this.listAllScanner();
			for (Scanner scanner: scanners) {
				if(StrKit.equals(ip,scanner.getIpAddress())){
					ret = scanner;
					CacheKit.put("findScannerByIp",ip,ret);
					break;
				}
			}
		}
		if(ret==null){
			ret =dao.template("scanner.findScannerByIp",ip).findFirst();
			CacheKit.put("findScannerByIp",ip,ret);
		}
		return ret;
	}

	/***
	 * 查询自动上线扫描枪
	 * @return
	 */
	public Scanner findAutoOnlineScanner(){
		List<Scanner> scanners = this.listAllScanner();
		for (Scanner scanner : scanners) {
			if(scanner.getScannerType().intValue()==Scanner.AUTO_ENTER){
				return scanner;
			}
		}
		return null;
	}

	/***
	 * 查询自动下线扫描枪
	 * @return
	 */
	public Scanner findAutoOfflineScanner(){
		List<Scanner> scanners = this.listAllScanner();
		for (Scanner scanner : scanners) {
			if(scanner.getScannerType().intValue()==Scanner.AUTO_EXIT){
				return scanner;
			}
		}
		return null;
	}

	private void clearCache(){
		CacheKit.removeAll("scanner");
		CacheKit.removeAll("findScannerById");
		CacheKit.removeAll("findScannerByIp");
		CacheKit.removeAll("listScannerByType");
	}



	
	public Ret paginate(Integer offset,Integer pageSize) {
        Integer pageNumber=offset/pageSize+1;
		Page<Scanner> paginate = dao.template("scanner.paginate").paginate(pageNumber, pageSize);
		List<Scanner> list = paginate.getList();
		for (Scanner scanner: list ) {
			Account account = accountService.findByEmployeeNo(scanner.getEmployeeNo());
			if(account!=null){
				String realName = account.getRealName();
				if(realName!=null){
					scanner.setUserName(realName);
				}
			}
		}
		Ret ret = Ret.by("total", paginate.getTotalRow()).set("rows", list);
		return ret;
	}
	
	public List<Record> manualEnterBindInfo(){
		return Db.template("scanner.findBindInfo",Scanner.MANUAL_ENTER).find();
	}
	
	public List<Record> manualExitBindInfo(){
		return Db.template("scanner.findBindInfo",Scanner.MANUAL_EXIT).find();
	}
	
	public Ret save(Scanner scanner) {
		if(isIpAddressExists(scanner.getIpAddress(), -1)) {
			return Ret.fail("msg", "IP地址已存在，请输入其他IP地址");
		}
		
		scanner.setUpdateTime(new Date());
		scanner.setScannerStatus(Scanner.STATUS_OK);
		scanner.save();
		clearCache();
		return Ret.ok("msg","操作成功");
	}

	
	public Ret update(Scanner scanner) {
		if(isIpAddressExists(scanner.getIpAddress(), scanner.getId())) {
			return Ret.fail("msg", "IP地址已存在，请输入其他IP地址");
		}
		
		scanner.setUpdateTime(new Date());
		scanner.update();
		clearCache();
		return Ret.ok("msg","操作成功");
	}
	
	
	public Ret delete(String id) {
		dao.deleteById(id);
		clearCache();
		return Ret.ok("msg","操作成功");
	}
	
	
	/**
	 * 锁定扫描枪
	 */
	public Ret lock(Integer scannerId) {
		int n = Db.template("scanner.updateScannerLockStatus",Scanner.STATUS_LOCK_ID,scannerId).update();
		if (n > 0) {
			return Ret.ok("msg", "锁定成功");
		} else {
			return Ret.fail("msg", "锁定失败");
		}
	}

	/**
	 * 解锁
	 */
	public Ret unlock(Integer scannerId) {
		int n = Db.template("scanner.updateScannerLockStatus",Scanner.STATUS_OK,scannerId).update();
		if (n > 0) {
			return Ret.ok("msg", "解锁成功");
		} else {
			return Ret.fail("msg", "解锁失败，可能是账户未激活，请查看账户详情");
		}
	}

	/**
	 * 绑定账号
	 * @param id
	 * @param employeeNo
	 * @return
	 */
	public Ret bindAccount(Integer id,String employeeNo) {
		String sql="select * from account where employee_no=?";
		Account account = Account.dao.findFirst(sql,employeeNo);
		if(account==null) {
			return Ret.fail("msg","无法根据员工号找到对应的员工信息");
		}
		
		if(account.isStatusLockId()) {
			return Ret.fail("msg","员工已被锁定");
		}

		Scanner scanner = this.findById(id);
		boolean ret=scanner.setEmployeeNo(employeeNo)
						   .setUpdateTime(new Date())
						   .update();
		if(ret) {
			return Ret.ok("msg","操作成功");
		}else {
			return Ret.fail("msg","操作失败");
		}
	}

	/**
	 * 根据IP地址寻找用户账户
	 * @param ipAddress
	 * @return
	 */
	public Account findAccountByIp(String ipAddress) {
		Scanner scanner=this.findByIp(ipAddress);
		if(scanner==null) {
			return null;
		}
		String employeeNo=scanner.getEmployeeNo();
		return accountService.findByEmployeeNo(employeeNo);
	}

	public String  getAccountIdByScannerId(String ipAddress){
		Scanner scanner=this.findByIp(ipAddress);
		if(scanner==null){
			return  "";
		}
		String employeeNo=scanner.getEmployeeNo();
		if(StrKit.isBlank(employeeNo)){
			return "";
		}
		Account account = accountService.findByEmployeeNo(employeeNo);
		if(account==null){
			return  "";
		}
		return account.getId();
	}

	/**
	 * 绑定用户
	 * @param ipAddress
	 * @param employeeNo
	 */
	public void bindAccountByIp(String ipAddress,String employeeNo) {
		String sql="update t_scanner_employee set employee_no = ? where ip = ?";
		Db.update(sql,ipAddress,employeeNo);
	}


	/***
	 * IP地址重复性判断
	 * @param ipAddress
	 * @param id
	 * @return
	 */
	private boolean isIpAddressExists(String ipAddress,Integer id) {
		ipAddress=ipAddress.toLowerCase().trim();
		String sql="select top 1 id from t_scanner_employee where lower(ip_address) = ? and id != ?";
		String ret=Db.queryStr(sql,ipAddress,id);
		return ret!=null;
	}

}